import React, { Component } from 'react'
import {
  Card,
  List,
  Button
} from 'antd'
import { ArrowLeftOutlined } from '@ant-design/icons'
import { BASE_IMG_URL } from '../../utils/constants'
import { APIGetCategory } from '../../api'
const Item = List.Item
export default class ProductDetail extends Component {
  state = {
    cName1: '',
    cName2: ''
  }


  async componentDidMount() {
    const { pCategoryId, categoryId } = this.props.location.state.product
    if(pCategoryId === '0') {
      const result = await APIGetCategory(categoryId)
      const cName1 = result.data.name
      this.setState({cName1})
    } else {
      /* 
        后面的请求是在前面请求成功返回之后才发：
        const result1 = await APIGetCategory(pCategoryId)
        const result2 = await APIGetCategory(categoryId)
        const cName1 = result1.data.name
        const cName2 = result2.data.name
      */
      const results = await Promise.all([APIGetCategory(pCategoryId), APIGetCategory(categoryId)])
      const cName1 = results[0].data.name
      const cName2 = results[0].data.name
      this.setState({
        cName1, 
        cName2
      })
    }
  }

  render() {
    const { cName1, cName2 } = this.state
    const { name, desc, price, imgs, detail } = this.props.location.state.product
    const title = (
      <span>
        <Button type="link" onClick={()=>{this.props.history.go(-1)}}>
          <ArrowLeftOutlined style={{color: 'green', marginRight: 15, fontSize: 20}}/>
        </Button>
        <span>商品详情</span>
      </span>
    )
    return (
      <Card title={title} className='product_detail'>
        <List>
          <Item>
            <span className='left'>商品名称:</span>
            <span>{name}</span>
          </Item>
          <Item>
            <span className='left'>商品描述:</span>
            <span>{desc}</span>
          </Item>
          <Item>
            <span className='left'>商品价格:</span>
            <span>{price}元</span>
          </Item>
          <Item>
            <span className='left'>所属分类:</span>
            <span>{cName1} {cName2 ? ' --> ' + cName2 : ''}</span>
          </Item>
          <Item>
            <span className='left'>商品图片:</span>
            {
              imgs.map(img => (
                <img key={img} className='product_img' src={BASE_IMG_URL + img} alt="img" />
                ))
            }
          </Item>
          <Item>
            <span className='left'>商品详情:</span>
            <span dangerouslySetInnerHTML={{__html: detail}}></span>
          </Item>
        </List>
      </Card>
    )
  }
}
